package com.cn.shuangzi.ad.activity;

import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.CSJAdError;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.activity.SZSplashActivity;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.R;
import com.cn.shuangzi.ad.bean.ADPlatform;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.tt.SplashShownManager;
import com.cn.shuangzi.ad.util.tt.TTAdManagerHolder;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.util.AdError;

import java.util.List;


public abstract class ADSplashActivity extends SZSplashActivity implements ADManager.OnSplashADLoadListener {

    private TTAdNative mTTAdNative;
    private int SPLASH_SHOW_TIME_NORMAL = 1500;
    private final int FETCH_DELAY = ADConst.TIME_OUT;
    private long beginTime;
    private List<ADPlatform> adPlatformList;

    private View.OnClickListener onVipSkipClickListener;
    private Handler handlerCloseSplash;
    private boolean isShownAd;

    @Override
    public void onPreCreated() {
        onPreInitAd();
        initCutDown();
        isDealToNext = false;
        isShownAd = false;
        isShowCutDown = false;
        resetSplashManager();
    }

    public void autoCloseSplash() {
        //未知情况出现卡死的情况下，主动执行跳转
        try {
            if (handlerCloseSplash != null) {
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplash = new Handler();
        handlerCloseSplash.postDelayed(new Runnable() {
            @Override
            public void run() {
                ADUtil.logError("是否需要自动关闭：" + !isShownAd);
                if (!isShownAd) {
                    if (!isFinishing()) {
                        ADUtil.logError("=====执行自动关闭=====");
                        toMain();
                    }
                }
            }
        }, getSplashCloseDelayTimeInNoAd());
    }

    private void initCutDown() {
        txtSkip.setVisibility(View.GONE);
        txtSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toMainByDelay(true);
            }
        });
    }

    public void fetchSelfAD() {
        fetchSelfAD(null);
    }

    public void fetchSelfAD(ADManager.OnSplashADLoadListener onSplashADLoadListener) {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(ADUtil.getChannel(this), getPackageName(), String.valueOf(ADUtil.getVersionCode(this)), onSplashADLoadListener);
    }

    public void fetchSelfADToHome() {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(ADUtil.getChannel(this), getPackageName(), String.valueOf(ADUtil.getVersionCode(this)), this);
    }

    public void fetchSplashAD() {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSplash(ADUtil.getChannel(this), getPackageName(), String.valueOf(ADUtil.getVersionCode(this)), this);
    }

    public void fetchTTSplashAD() {
        try {
            int height = 0;
            int width = 0;
            try {
                width = ADUtil.getScreenWidth(this);
                if (isFullScreenMode()) {
                    try {
                        height = ADUtil.getScreenHeight(this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    height = splash_container.getHeight();
                }
            } catch (Exception e) {
            }
            width = width <= 0 ? 1080 : width;
            height = height <= 0 ? 1920 : height;
            ADUtil.logError("===============拉取穿山甲=================");
            mTTAdNative = TTAdManagerHolder.getInstance().createAdNative(this);
            //开屏广告参数
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(getTTSplashId())
                    .setSupportDeepLink(true)
                    .setMediationAdSlot(
                            new MediationAdSlot.Builder()
                                    .setVolume(0)
                                    .setMuted(true)
                                    .setAllowShowCloseBtn(true).build())
                    .setExpressViewAcceptedSize(ADUtil.px2dip(width), ADUtil.px2dip(height))
                    .setImageAcceptedSize(width, height)
                    .build();
            //调用开屏广告异步请求接口
            mTTAdNative.loadSplashAd(adSlot, new TTAdNative.CSJSplashAdListener() {

                @Override
                public void onSplashLoadSuccess(CSJSplashAd csjSplashAd) {
                    ADUtil.logError("=======穿山甲加载成功======");
                }

                @Override
                public void onSplashLoadFail(CSJAdError csjAdError) {

                    ADUtil.logError("穿山甲onError|Code:" + csjAdError.getCode() + "：" + csjAdError.getMsg());
                    fetchNextPlatformAd();
                }

                @Override
                public void onSplashRenderSuccess(CSJSplashAd csjSplashAd) {
                    ADUtil.logError("=======穿山甲显示成功======:" + csjSplashAd);
                    if (csjSplashAd == null) {
                        fetchNextPlatformAd();
                        return;
                    }

                    rltBottom.setVisibility(isFullScreenMode() ? View.GONE : View.VISIBLE);

                    if (isShowUserDefineSkip()) {
                        csjSplashAd.hideSkipButton();
                    }
                    splash_container.removeAllViews();
                    csjSplashAd.showSplashView(splash_container);
                    //设置SplashView的交互监听器
                    csjSplashAd.setSplashAdListener(new CSJSplashAd.SplashAdListener() {
                        @Override
                        public void onSplashAdShow(CSJSplashAd csjSplashAd) {
                            SplashShownManager.getInstance().setSplashShown(true);
                            ADUtil.setFirstUseAdTime();
                            isShownAd = true;
                            ADUtil.logError("=====头条广告展示=====");
                            showCutDown();
                        }

                        @Override
                        public void onSplashAdClick(CSJSplashAd csjSplashAd) {
                            ADUtil.logError("=====头条广告点击=====");
                        }

                        @Override
                        public void onSplashAdClose(CSJSplashAd csjSplashAd, int i) {
                            ADUtil.logError("=======穿山甲关闭======");
                            toNext();
                        }
                    });
                }

                @Override
                public void onSplashRenderFail(CSJSplashAd csjSplashAd, CSJAdError csjAdError) {

                    ADUtil.logError("穿山甲onError|Code:" + csjAdError.getCode() + "：" + csjAdError.getMsg());

                    fetchNextPlatformAd();
                }
            }, FETCH_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
            toNext();
        }
    }


    /**
     * 拉取开屏广告，开屏广告的构造方法有3种，详细说明请参考开发者文档。
     */
    public void fetchGDTSplashAD() {
        try {
            ADUtil.logError("==========拉取广点通=========");
            String posId = getGDTSplashId();
            new SplashAD(this, posId, new SplashADListener() {
                @Override
                public void onADDismissed() {
                    toNext();
                }

                @Override
                public void onNoAD(AdError adError) {
                    ADUtil.logError("广点通Error|Code:" + adError.getErrorCode() + "|Msg:" + adError.getErrorMsg());
                    fetchNextPlatformAd();
                }

                @Override
                public void onADPresent() {
                }

                @Override
                public void onADClicked() {
                }

                @Override
                public void onADTick(long l) {
                    isShownAd = true;
                    ADUtil.logError("广点通开屏剩余时间：" + l);
                    showCutDown();
                }

                @Override
                public void onADExposure() {
                    SplashShownManager.getInstance().setSplashShown(true);
                    ADUtil.setFirstUseAdTime();
                    ADUtil.logError("=====广点通广告展示=====");
                }

                @Override
                public void onADLoaded(long l) {
                    ADUtil.logError("广点通广告onADLoaded:" + l);

                }
            }, 0).fetchAndShowIn((ViewGroup) findViewById(R.id.splash_container));
        } catch (Exception e) {
            e.printStackTrace();
            toNext();
        }
    }


    private boolean isDealToNext = false;

    private void toNext() {
        if (!isDealToNext) {
            next();
        }
        isDealToNext = true;
    }

    private boolean isShowCutDown = false;

    private void showCutDown() {
        if (isShowCutDown) {
            return;
        }
        isShowCutDown = true;
        if (isShowVipSkipBtn()) {
            txtVipSkip.setVisibility(View.VISIBLE);
            if (onVipSkipClickListener == null) {
                txtVipSkip.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            startActivity(getVipActivity());
                        } catch (Exception e) {
                        }
                    }
                });
            }
            txtVipSkip.setOnClickListener(onVipSkipClickListener);
        } else {
            txtVipSkip.setVisibility(View.GONE);
        }
        if (isShowUserDefineSkip()) {
            txtSkip.setVisibility(View.VISIBLE);
            txtSkip.setText("跳过");
        } else {
            txtSkip.setVisibility(View.GONE);
        }
    }

    private void toMainByDelay(boolean isNowSkip) {
        if (isNowSkip) {
            ADUtil.logError("=====执行立即跳转=====");
            toMain();
        } else {
            long delay = getDelayFinishTime();
            ADUtil.logError("=====执行延时跳转=====" + delay);
            toMain(delay);
        }
    }

    private long getDelayFinishTime() {
        long errorTime = System.currentTimeMillis();
        long remainderTime = SPLASH_SHOW_TIME_NORMAL - (errorTime - beginTime);
        return remainderTime > 0 ? remainderTime : 0;
    }

    @Override
    public void onFetchAdSuccess(List<ADPlatform> adPlatformServiceList) {
        ADUtil.logError("adPlatformList:" + adPlatformServiceList);
        if (isTTFirstMode()) {
            if (SZValidatorUtil.isValidList(adPlatformServiceList)) {
                String adList = "[{\"adExtendData\":\"{\\\"lastSecond\\\":5000,\\\"showType\\\":2,\\\"clickEyeMode\\\":\\\"always\\\"}\",\"adIsOpen\":true,\"adSupportType\":\"TOUTIAO\",\"adType\":\"LAUNCH_AD\",\"adVid\":\"a9e7bcfcd360436078c9045b299fc806\"},{\"adExtendData\":\"{\\\"lastSecond\\\":5000,\\\"showType\\\":2}\",\"adIsOpen\":true,\"adSupportType\":\"GDT\",\"adType\":\"LAUNCH_AD\",\"adVid\":\"574536e52fa2e1616b17a3ad6a839898\"}]";
                adPlatformList = new Gson().fromJson(adList, new TypeToken<List<ADPlatform>>() {
                }.getType());
            }
        }else {
            adPlatformList = adPlatformServiceList;
        }
        if (SZValidatorUtil.isValidList(adPlatformList)) {
            try {
                final ADPlatform adPlatform = adPlatformList.get(ADConst.LOAD_AD_INDEX);
                if (adPlatform.isAdIsOpen()) {
                    fetchPlatformAd(adPlatform);
                } else {
                    toMainByDelay(false);
                }
            } catch (Exception e) {
                e.printStackTrace();
                toMainByDelay(false);
            }
        } else {
            toMainByDelay(false);
        }
    }

    private void fetchNextPlatformAd() {
        if (adPlatformList != null && adPlatformList.size() > 0) {
            fetchPlatformAd(adPlatformList.get(0));
        } else {
            toMainByDelay(false);
        }
    }

    private void fetchSelfSplashAD(ADPlatform adPlatform) {
        //todo 显示自营广告
    }

    private void fetchPlatformAd(final ADPlatform adPlatform) {
        if (adPlatform != null) {
            if(!TTAdManagerHolder.isInitSuccess()) {
                ADManager.getInstance().addOnAdInitDoneListener(new ADManager.OnAdInitDoneListener() {
                    @Override
                    public void onTTAdInitDone(boolean isSuccess) {
                        ADManager.getInstance().removeOnAdInitDoneListener(this);
                        if(isSuccess) {
                            fetchPlatformAdReal(adPlatform);
                        }else{
                            fetchPlatformAd(adPlatform);
                        }
                    }
                });
                ADManager.getInstance().initAd(false);
            }else{
                fetchPlatformAdReal(adPlatform);
            }
        } else {
            toMainByDelay(false);
        }
    }
    private void fetchPlatformAdReal(ADPlatform adPlatform) {
        if (adPlatform != null) {
            adPlatformList.remove(adPlatform);
            switch (adPlatform.getAdSupportType()) {
                case ADConst.AD_PLATFORM_TT:
                    fetchTTSplashAD();
                    break;
                case ADConst.AD_PLATFORM_GDT:
                    fetchGDTSplashAD();
                    break;
                default:
                    toMainByDelay(false);
            }
        } else {
            toMainByDelay(false);
        }
    }

    public void init(boolean isShowAd) {
        init(isShowAd, 1000);
    }

    public void init(boolean isShowAd, long delayToMain) {
        SZApp.getInstance().init();
        dealAd(isShowAd, delayToMain);
    }

    public void dealAd(boolean isShowAd) {
        dealAd(isShowAd, 1000);
    }

    public void dealAd(boolean isShowAd, long delayToMain) {
        if (isShowAd) {
            autoCloseSplash();
            ADUtil.logError("设置自动关闭成功");
            fetchSplashAD();
        } else {
            ADUtil.logError("不展示广告，直接进主页");
            toMain(delayToMain);
        }
    }

    @Override
    public void onFetchAdError() {
        toMainByDelay(false);
    }

    public long getAdShowTimeUserDefine() {
        return 0;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyHandlerMessage();
    }

    private void destroyHandlerMessage() {
        try {
            if (handlerCloseSplash != null) {
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplash = null;
    }

    private void resetSplashManager(){
        SplashShownManager.getInstance().setSplashShown(false);
    }

    public long getSplashCloseDelayTimeInNoAd() {
        return 6000;
    }

    @Override
    public boolean isShowTitleInit() {
        return false;
    }

    public View.OnClickListener getOnVipSkipClickListener() {
        return onVipSkipClickListener;
    }

    public void setOnVipSkipClickListener(View.OnClickListener onVipSkipClickListener) {
        this.onVipSkipClickListener = onVipSkipClickListener;
    }

    public void onPreInitAd() {
    }

    public abstract String getTTSplashId();

    public abstract String getGDTSplashId();

    public abstract void onCreated();

    public abstract int getSplashRes();

    public abstract int getAppIconRes();

    public abstract int getAppNameRes();

    public abstract int getAppNameColorRes();

    public abstract Class getHomeActivity();

    public abstract boolean isShowVipSkipBtn();

    public abstract Class getVipActivity();

    public abstract boolean isFullScreenMode();

    public boolean isShowUserDefineSkip() {
        return false;
    }

    public boolean isTTFirstMode() {
        return false;
    }
}

